<!DOCTYPE html>
<html>
<head>
<script src="resources/recv.js"></script>
<script>
if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

var totalExpectedReplies = 0;
var receivedMessages = [];

function tryPostMessage(win, origin, shouldExpectReply) {
    try {
        win.postMessage("Trying origin=" + origin, origin);
        if (shouldExpectReply)
            totalExpectedReplies++;
    } catch(ex) {
        log("Error sending message to " + origin + ". " + ex);
    }
}

function receiveAndSort(e) {
    var msg = extractMessage(e);
    receivedMessages.push(msg);
    if (receivedMessages.length == totalExpectedReplies) {
        receivedMessages.sort();
        receivedMessages.map(log);
        if (window.testRunner)
            testRunner.notifyDone();
    }
}

addEventListener("message", receiveAndSort, false);

function test() {
    var win127 = document.getElementById('iframe-127').contentWindow;

    // Should succeed:
    tryPostMessage(win127, "http://127.0.0.1:8000", true);
    tryPostMessage(win127, "http://127.0.0.1:8000/", true);
    tryPostMessage(win127, "http://127.0.0.1:8000/foo", true);
    tryPostMessage(win127, "http://127.0.0.1:8000/foo?bar#baz", true);
    tryPostMessage(win127, "http://127.0.0.1:8000/foo?bar", true);
    tryPostMessage(win127, "http://user:pass@127.0.0.1:8000/foo?bar#baz", true);

    // Should fail:
    tryPostMessage(win127, "http://127.0.0.1:9090", false);
    tryPostMessage(win127, "http://127.0.0.1", false);
    tryPostMessage(win127, "https://127.0.0.1", false);
    tryPostMessage(win127, "https://127.0.0.1:8000", false);
    tryPostMessage(win127, "http://www.example.com", false);
    tryPostMessage(win127, "asdf:", false);

    // Should throw syntax error:
    tryPostMessage(win127, "", false);
    tryPostMessage(win127, "asdf", false);
    tryPostMessage(win127, "/tmp/foo", false);
    tryPostMessage(win127, "//localhost", false);
    tryPostMessage(win127, "http:", false);
}

</script>
<body onload="test()">
<div>window.location.href = <script>document.write(window.location.href);</script></div>
<div><iframe src="http://127.0.0.1:8000/security/postMessage/resources/post-message-listener.html"
  id="iframe-127" width="800" height="300" style="border: 1px solid black;"></iframe>
<div id="result">waiting...</div>
</body>
</html>
